package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class SystemLogUtil {

    @Autowired
    ISystemLogService systemLogService;

    public void writeLog(JoinPoint joinPoint){

        //如果是日志的service,就不记录,防止出现死循环
        if(joinPoint.getTarget() instanceof  ISystemLogService){
            return;
        }

        System.out.println("-----写入日志-----");
        SystemLog log = new SystemLog();
        //操作时间
        log.setOpTime(new Date());
        //操作ip
        log.setOpIp(UserContext.getRequest().getRemoteAddr());
        //操作用户
        log.setOpUser(UserContext.getCurrentUser());
        //类名
        String className = joinPoint.getTarget().getClass().getName();
        //方法名
        String methodName = joinPoint.getSignature().getName();
        System.out.println(className+":"+methodName);
        log.setFunction(className+":"+methodName);

        try {
            //执行的参数
            log.setParams(new ObjectMapper().writeValueAsString(joinPoint.getArgs()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //添加到数据库中
        systemLogService.insert(log);
    }

}
